package com.ifast.hnzk.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.ifast.common.annotation.Log;
import com.ifast.common.base.BaseController;
import com.ifast.common.exception.IFastException;
import com.ifast.common.utils.*;
import com.ifast.hnzk.domain.HnzkFile;
import com.ifast.hnzk.service.HnzkFileService;
import com.ifast.oss.domain.FileDO;
import com.ifast.oss.service.FileService;
import com.ifast.sys.domain.UserDO;
import com.ifast.sys.service.UserService;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/hnzk/file/")
public class HnzkFileController extends BaseController {

    @Value("${hnzk_upload_path}")
    private String upload_path;
    @Value("${hnzk_upload_file_path}")
    private String hnzk_upload_file_path;
    @Autowired
    private HnzkFileService hnzkFileService;
    @Autowired
    private  FileService sysFileService;
    @Autowired
    private UserService userService;
   // @Autowired
    //private ResourceLoader resourceLoader;
    @Log("上传封面")
    @RequestMapping("add")
    @ResponseBody
    public Result<Map> addFile(@RequestParam("file") MultipartFile file){
        String formatDir = getformatDir();
        String saveDir = upload_path+"/"+formatDir;
        File file2= new File(saveDir);
        if (!file2.exists()) {
            file2.mkdirs();
        }

        String fileName = file.getOriginalFilename();
        String fileFormat = fileName.substring(fileName.lastIndexOf("."));
        String uuid = UUIDUtils.get();
        String saveName = uuid+fileFormat;
        try{
            String path = saveDir+"/"+saveName;
            File dest = new File(path);
            file.transferTo(dest);
            //把文件信息插入到数据库
            HnzkFile hnzkFile = new HnzkFile();
            hnzkFile.setFileCreatedate(new Date());
            hnzkFile.setFileFormat(fileFormat);
            hnzkFile.setFileName(fileName);
            hnzkFile.setFileSize(file.getSize());
            hnzkFile.setFileType(file.getContentType());
            hnzkFile.setFileStatus(0);
            hnzkFile.setFileFid(uuid);
            hnzkFile.setFilePath(path);
            hnzkFileService.insert(hnzkFile);
        }catch (Exception e){
            e.printStackTrace();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("path", "/hnzk/file/show?fileName="+saveName+"&formatDir="+formatDir);
        map.put("fileid", uuid);
        return Result.ok(map);

    }
    @Log("新闻封面图片上传")
    @RequestMapping("addFmImg")
    @ResponseBody
    public Result<Map> addFmImg(@RequestParam("file") MultipartFile file){
        String formatDir = getformatDir();
        String saveDir = upload_path+"/"+formatDir;
        File file2= new File(saveDir);
        if (!file2.exists()) {
            file2.mkdirs();
        }
        String ImgName = file.getOriginalFilename();
        String imgFormat = ImgName.substring(ImgName.lastIndexOf("."));
        String uuid = UUIDUtils.get();
        String saveImgname = uuid + imgFormat;
        String sysPath = saveDir+"/"+"sys_"+saveImgname;
        String smallPath = saveDir+"/"+"small_"+saveImgname;
        String imgPath = saveDir+"/"+"img_"+saveImgname;
        try{
            //写一份新闻列表的展示图片
            Thumbnails.of(file.getInputStream()).size(235, 135).keepAspectRatio(false).toFile(new File(imgPath));
            //写一份首页展示图片
            Thumbnails.of(file.getInputStream()).size(150, 105).keepAspectRatio(false).toFile(new File(smallPath));
            //写一份到后台展示是小图片
            Thumbnails.of(file.getInputStream()).size(50, 50).keepAspectRatio(false).toFile(new File(sysPath));
        }catch (Exception e){
            e.printStackTrace();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("sysPath", "/hnzk/file/show?fileName=sys_"+saveImgname+"&formatDir="+formatDir);
        map.put("smallPath", "/hnzk/file/show?fileName=small_"+saveImgname+"&formatDir="+formatDir);
        map.put("imgPath", "/hnzk/file/show?fileName=img_"+saveImgname+"&formatDir="+formatDir);
        return Result.ok(map);
    }

    @Log("案例封面图片上传")
    @RequestMapping("addExmapleFmImg")
    @ResponseBody
    public Result<Map> addExmapleFmImg(@RequestParam("file") MultipartFile file){
        String formatDir = getformatDir();
        String saveDir = upload_path+"/"+formatDir;
        File file2= new File(saveDir);
        if (!file2.exists()) {
            file2.mkdirs();
        }
        String ImgName = file.getOriginalFilename();
        String imgFormat = ImgName.substring(ImgName.lastIndexOf("."));
        String uuid = UUIDUtils.get();
        String saveImgname = uuid + imgFormat;
        String sysPath = saveDir+"/"+"sys_"+saveImgname;
        String imgPath = saveDir+"/"+"img_"+saveImgname;
        try{
            //写一份案例列表的展示图片
            Thumbnails.of(file.getInputStream()).size(250, 140).keepAspectRatio(false).toFile(new File(imgPath));
            //写一份到后台展示是小图片
            Thumbnails.of(file.getInputStream()).size(50, 50).keepAspectRatio(false).toFile(new File(sysPath));
        }catch (Exception e){
            e.printStackTrace();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("sysPath", "/hnzk/file/show?fileName=sys_"+saveImgname+"&formatDir="+formatDir);
        map.put("imgPath", "/hnzk/file/show?fileName=img_"+saveImgname+"&formatDir="+formatDir);
        return Result.ok(map);
    }

    @Log("删除图片")
    @RequestMapping("deleteImg")
    @ResponseBody
    public Result<String> deleteImg(String fileId){

        //log.info("fileId = "+fileId);
        if(fileId!=null && !fileId.isEmpty()){
            Wrapper<HnzkFile> wrapper = new EntityWrapper<HnzkFile>();
            wrapper.eq("fileFid",fileId);
            HnzkFile hnzkFile = hnzkFileService.selectOne(wrapper);
            String imgpath =  hnzkFile.getFilePath();
            File imgFile  = new File(imgpath);
            if(imgFile.exists()){
                imgFile.delete();
            }
            hnzkFileService.deleteById(hnzkFile.getId());
        }
        return  Result.ok();
    }
    @Log("显示单张封面图片")
    @RequestMapping("/show")
    @ResponseBody
    public void showPhotos(String fileName,String formatDir) {
        HttpServletResponse response = HttpContextUtils.getHttpServletResponse();
        response.setContentType("image/jpeg/jpg/png/gif/bmp/tiff/svg");

        File file = new File(upload_path + "/" + formatDir + "/" + fileName);
        try {
            if (file.exists()) {
                FileInputStream in = new FileInputStream(file);
                OutputStream os = response.getOutputStream();
               // response.reset();
                byte[] b = new byte[1024];
                while (in.read(b) != -1) {
                    os.write(b);
                }
                in.close();
                os.close();
                os.flush();

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Log("得到日期格式如：20190619")
    private String getformatDir() {
        String format = DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN_8);
        String path = format ;
        return path;
    }

    @Log("上传头像")
    @ResponseBody
    @PostMapping("/uploadImg")
    public Result<?> uploadImg(@RequestParam("avatar_file") MultipartFile file, String avatar_data, HttpServletRequest request){
        String fileName = file.getOriginalFilename();
        String formatDir = getformatDir();
        String saveDir = upload_path+"/"+formatDir;
        File file2= new File(saveDir);
        if (!file2.exists()) {
            file2.mkdirs();
        }
        String saveName = UUIDUtils.get() + fileName.substring(fileName.lastIndexOf("."));
        String url = "";
        // 获取图片后缀
        String prefix = fileName.substring((fileName.lastIndexOf(".") + 1));
        String[] str = avatar_data.split(",");
        // 获取截取的x坐标
        int x = (int) Math.floor(Double.parseDouble(str[0].split(":")[1]));
        // 获取截取的y坐标
        int y = (int) Math.floor(Double.parseDouble(str[1].split(":")[1]));
        // 获取截取的高度
        int h = (int) Math.floor(Double.parseDouble(str[2].split(":")[1]));
        // 获取截取的宽度
        int w = (int) Math.floor(Double.parseDouble(str[3].split(":")[1]));
        // 获取旋转的角度
        int r = Integer.parseInt(str[4].split(":")[1].replaceAll("}", ""));

        try {
            BufferedImage cutImage = ImageUtils.cutImage(file, x, y, w, h, prefix);
            BufferedImage rotateImage = ImageUtils.rotateImage(cutImage, r);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(rotateImage, prefix, out);
            // 转换后存入数据库
            byte[] b = out.toByteArray();

            String path = saveDir+"/"+saveName;
            if(bytesToMyFile(b, path)){
                url =   "/hnzk/file/show?fileName="+saveName+"&formatDir="+formatDir;
            }
        } catch (Exception e) {
            throw new IFastException("图片裁剪错误！！");
        }
        Map<String, Object> result = new HashMap<>();
        FileDO sysFile = new FileDO(FileType.fileType(fileName), url, new Date());
        if (sysFileService.insert(sysFile)) {
            UserDO userDO = userService.selectById(getUserId());
            userDO.setPicId(sysFile.getId());
            if (userService.updateById(userDO)) {
                result.put("url", sysFile.getUrl());
            }
        }
        return Result.ok(result);
    }
    public boolean bytesToMyFile(byte[] bytes, final String filePath) {
        File file = new File(filePath);
        OutputStream os = null;
        BufferedOutputStream bos = null;
        try {
            os = new FileOutputStream(file);
            bos = new BufferedOutputStream(os);
            bos.write(bytes);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return  false;
        } catch (IOException e) {
            e.printStackTrace();
            return  false;
        } finally {
            if (null != bos) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    return  false;
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    return  false;
                }

            }
        }
        return true;

    }
    @Log("上传文件")
    @RequestMapping("uploadFile")
    @ResponseBody
    public Result<?> uploadFile(MultipartFile file,String affixId){
        String formatDir = getformatDir();
        String saveDir = hnzk_upload_file_path+"/"+formatDir;
        File file2= new File(saveDir);
        if (!file2.exists()) {
            file2.mkdirs();
        }

        try{
            if(file!=null){
                String fileName = file.getOriginalFilename();
                String fileFormat = fileName.substring(fileName.lastIndexOf("."));
                String saveName = UUIDUtils.get()+fileFormat;
                String path = saveDir+"/"+saveName;
                File dest = new File(path);
                file.transferTo(dest);
                //把文件信息插入到数据库
                HnzkFile hnzkFile = new HnzkFile();
                hnzkFile.setFileCreatedate(new Date());
                hnzkFile.setFileFormat(fileFormat);
                hnzkFile.setFileName(fileName);
                hnzkFile.setFileSize(file.getSize());
                hnzkFile.setFileType(file.getContentType());
                hnzkFile.setFileStatus(0);
                hnzkFile.setFileFid(affixId);
                hnzkFile.setFilePath(path);
                hnzkFileService.insert(hnzkFile);
            }
            return  Result.ok();
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("affixId:"+affixId);
        return  Result.fail();
    }
    @Log("下载文件")
    @RequestMapping("download")
    @ResponseBody
    public void download(@RequestParam("id") Long id,HttpServletResponse response){
        try{
            HnzkFile hnzkFile = hnzkFileService.selectOne(new EntityWrapper<HnzkFile>().eq("id",id));
            if(hnzkFile!=null){
                //处理下载文件名中文乱码情况
                String downloadFileName = URLEncoder.encode(hnzkFile.getFileName(),"UTF-8");
                response.reset();
                response.setHeader("Content-Disposition", "attachment; filename=\""+downloadFileName+"\"");
                response.addHeader("Content-Length", "" + hnzkFile.getFileSize());
                response.setContentType("application/octet-stream; charset=UTF-8");
                File file = new File(hnzkFile.getFilePath());
                FileInputStream in = new FileInputStream(file);
                OutputStream os = response.getOutputStream();
                byte[] b = new byte[1024];
                while (in.read(b) != -1) {
                    os.write(b);
                }
                in.close();
                os.flush();
                IOUtils.write(b, os);
                IOUtils.closeQuietly(os);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @Log("删除文件")
    @RequestMapping("removeFile")
    @ResponseBody
    public Result<String> removeFile(@RequestParam("id")Long id){
        HnzkFile hnzkFile = hnzkFileService.selectOne(new EntityWrapper<HnzkFile>().eq("id",id));
        if(hnzkFile!=null){
            String path =  hnzkFile.getFilePath();
            File file  = new File(path);
            if(file.exists()){
                file.delete();
            }
            hnzkFileService.deleteById(hnzkFile.getId());
        }

        return  Result.ok();
    }
}
